using System;
using System.Collections.Generic;
using System.Text;

namespace Helpers
{
    public class UrlHelper
    {
        public static bool IsUrlCorrect(string url)
        {
            bool res = true;
            res &= url != null && url.Trim().Length > 0;
            res &= true;                                        // TBD !!! syntaxis of URL string validation must be here
            return res;
        }

        public static string ClearUrl(string url)
        {
            string res = url;
            while (res.Contains("//"))
                res = res.Replace("//", "/");
            if (url.Contains("//") && res.Contains(":"))
            {
                string[] urlParts = res.Split(':');
                string protokolName = urlParts[0];
                res = res.Insert(((string)(protokolName + ":")).Length, "/");
            }
            return res;
        }

        public static string GetDomainName(string url)
        {
            if (!url.Contains("."))
                return null;

            string urlWithOutProtokol = null;
            if (url.Contains("//"))
            {
                string[] parts = url.Trim().Replace("//", " ").Split(' ');
                if (parts.Length > 1)
                    urlWithOutProtokol = parts[1];
            }
            else
                urlWithOutProtokol = url;

            if (urlWithOutProtokol == null)
                return null;

            string urlWithOutProtokolAndQueryString = null;
            if (!urlWithOutProtokol.Contains("?"))
                urlWithOutProtokolAndQueryString = urlWithOutProtokol;
            else
            {
                string[] parts = urlWithOutProtokol.Split('?');
                if (parts.Length > 0)
                    urlWithOutProtokolAndQueryString = parts[0];
            }

            if (urlWithOutProtokolAndQueryString == null)
                return null;

            if (!urlWithOutProtokolAndQueryString.Contains("/"))
                return urlWithOutProtokolAndQueryString;
            else
            {
                string[] parts = urlWithOutProtokolAndQueryString.Split('/');
                if (parts.Length < 1)
                    return null;

                string res = parts[0];
                if (!res.Contains("."))
                    return null;
                return res;
            }
        }
    }
}
